package cn.rjzjh.tapestry.busi.tools;

import java.io.Serializable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import redis.clients.jedis.Jedis;
import cn.rjzjh.commons.util.apiext.RedisClient;
import cn.rjzjh.tapestry.busi.SpringInit;
import cn.rjzjh.tapestry.busi.model.OptionItem;
import cn.rjzjh.tapestry.busi.service.ICommonService;
import cn.rjzjh.tapestry.tams.base.ParentPage;

public abstract class BusiAssit {

	private static Logger logger = LoggerFactory.getLogger(BusiAssit.class);

	/***
	 * 通过Hibernate查找对象
	 *
	 * @param clazz
	 * @param id
	 * @return
	 */
	public final static <T extends Serializable> T findById(Class clazz,
			Serializable id) {
		ICommonService common = (ICommonService) SpringInit.applicationContext
				.getBean("common");
		T ret = common.getHb().findById(clazz, id);
		return ret;
	}

	/***
	 * 通过Redis查找对象
	 *
	 * @param clazz
	 * @param key
	 * @return
	 */
	public final static <T extends Serializable> T findByRedis(Class clazz,
			Serializable key) {
		try {
			Jedis jedis = RedisClient.getConnection(SpringInit.conf);
			String jsonstr = jedis.get(String.valueOf(key));

			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss")
					.create();
			T retobj = (T) gson.fromJson(jsonstr, clazz);
			RedisClient.returnResource(jedis);
			return retobj;
		} catch (Exception e) {
			logger.error("连联Redis异常", e);
		}
		return null;
	}

	/****
	 * 把对象放到Redis中
	 *
	 * @param obj
	 *            对象
	 * @param key
	 *            key
	 * @param expire
	 *            有效期
	 */
	public final static <T extends Serializable> void putRedis(T obj,
			String key, Integer expire) {
		try {
			Jedis jedis = RedisClient.getConnection(SpringInit.conf);
			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss")
					.create();
			String json = gson.toJson(obj);

			jedis.set(key, json);
			// jedis.append(key, json);
			if (expire != null) {
				jedis.expire(key, expire);
			}
			// jedis.hmset(key, hash)//放到Redis中
			RedisClient.returnResource(jedis);
		} catch (Exception e) {
			logger.error("连联Redis异常", e);
		}
	}

	public final static <T extends Serializable> void putRedis(T obj, String key) {
		putRedis(obj, key, null);
	}

}
